package com.xuln.common.util;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.criterion.CriteriaSpecification;

/**
 * @author 徐炉南 xinlunan487@163.com
 */
@SuppressWarnings("unchecked")
public class BaseDaoUtil<T> {
	/**
	 * 得到实体类型
	 * 
	 * @lastmodify : 徐炉南 xinlunan487@163.com Aug 7, 2010
	 * @param clazz
	 * @param index
	 * @return Class<T>
	 */
	@SuppressWarnings( { "unchecked", "unused" })
	private Class<T> getSuperClassGenricType(Class clazz, int index) {
		java.lang.reflect.Type genType = clazz.getGenericSuperclass();
		if (genType instanceof ParameterizedType) {
			java.lang.reflect.Type params[] = ((ParameterizedType) genType).getActualTypeArguments();
			if (params != null && params.length >= index + 1)
				return (Class) params[index];
		}
		return null;
	}

	/**
	 * 去除hql的select子句，未考虑union的情况
	 */
	@SuppressWarnings("unused")
	public static String removeSelect(String hql) {
		int beginPos = hql.toLowerCase().indexOf("from");
		return hql.substring(beginPos);
	}

	/**
	 * 方法取自SpringSide. 去除hql的orderby子句
	 */
	@SuppressWarnings("unused")
	public static String removeOrders(String hql) {
		Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(hql);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			m.appendReplacement(sb, "");
		}
		m.appendTail(sb);
		return sb.toString();
	}

	/**
	 * 将联合查询的结果内容从Map或者Object[]转换为实体类型，如果没有转换必要则直接返回<br>
	 * 此方法测试后无任何实际意义，将每条数据的第一个字段返回回来
	 */
	@SuppressWarnings("unchecked")
	@Deprecated
	public List transformResults(List items, Class entityClass) {

		if (items.size() > 0) {
			if (items.get(0) instanceof Map) {
				ArrayList list = new ArrayList(items.size());
				for (int i = 0; i < items.size(); i++) {
					Map map = (Map) items.get(i);
					list.add(map.get(CriteriaSpecification.ROOT_ALIAS));
				}
				return list;
			} else if (items.get(0) instanceof Object[]) {
				ArrayList list = new ArrayList(items.size());
				int pos = 0;
				for (int i = 0; i < ((Object[]) items.get(0)).length; i++) {
					if (((Object[]) items.get(0))[i] != null && ((Object[]) items.get(0))[i].getClass() == entityClass) {
						pos = i;
						break;
					}
				}
				for (int i = 0; i < items.size(); i++) {
					list.add(((Object[]) items.get(i))[pos]);
				}
				return list;
			} else
				return items;
		} else
			return items;
	}
}
